package com.lagou.edu.service.impl;

import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.repository.UserRepository;
import com.lagou.edu.service.IUserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author 陶肖寅
 * @version V1.0
 * <p>
 * @date 2020-05-06 22:07
 * @email fromlx@126.com
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 * </p>
 */
@Service
public class UserService implements IUserSerivce {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveUser(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userRepository.save(user);
    }

    @Override
    public User getUserByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        Optional optional = userRepository.findOne(Example.of(user));
        if (optional.isPresent()){
            //表示已注册
            return (User) optional.get();
        }
        return null;
    }

    @Override
    public void saveToken(String email, String token) {
        redisTemplate.opsForValue().set("token#"+email,token);
    }

    @Override
    public Token isRegistered(String email) {
        Token tokenEntity = new Token();
        tokenEntity.setEmail(email);
        Example example = Example.of(tokenEntity);
        Optional optional = userRepository.findOne(example);
        if (optional.isPresent()){
            //表示已注册
            return (Token) optional.get();
        }
        return null;
    }

    @Override
    public Token findTokenByToken(String token) {
        Token tokenEntity = new Token();
        tokenEntity.setToken(token);
        Example example = Example.of(tokenEntity);
        Optional optional = userRepository.findOne(example);
        if (optional.isPresent()){
            //表示已注册
            return (Token) optional.get();
        }
        return null;
    }
}
